import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../store/user'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Home from '../views/Home.vue'
import Cart from '../views/Cart.vue'
import Product from '../views/Product.vue'

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'Login',
        component: Login
    },
    {
        path: '/register',
        name: 'Register',
        component: Register
    },
    {
        path: '/home',
        name: 'Home',
        component: Home,
        meta: { requiresAuth: true }
    },
    {
        path: '/cart',
        name: 'Cart',
        component: Cart,
        meta: { requiresAuth: true }
    },
    {
        path: '/product/:id',
        name: 'Product',
        component: Product,
        meta: { requiresAuth: true }
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes
})
router.beforeEach((to, from, next) => {
    const userStore = useUserStore()
    // 根路由动态重定向
    if (to.path === '/') {
        next(userStore.username ? '/home' : '/login')
    } else {
        // 验证需要登录的路由（meta.requiresAuth）
        if (to.meta.requiresAuth && !userStore.username) {
            next('/login') // 未登录跳转到登录页
        } else {
            next()
        }
    }
})

export default router